package com.hibernate.hrm.service.login;

import com.hibernate.hrm.entity.OperateLog;
import com.hibernate.hrm.dao.OperateLogRepository;
import com.hibernate.hrm.entity.User;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class OperateLogService {

    private final OperateLogRepository operateLogRepository;

    public OperateLogService(OperateLogRepository operateLogRepository) {
        this.operateLogRepository = operateLogRepository;
    }

    public void recordLoginLog(Integer userId, HttpServletRequest request, boolean success) {
        if (!success) {
            return; // 根据需求，登录失败不记录
        }

        OperateLog log = new OperateLog();
        log.setUserId(userId);
        log.setOperateType("login");
        log.setOperateDetail(String.format("用户ID[%d]从IP[%s]登录系统", userId, getClientIp(request)));
        log.setOperateTime(LocalDateTime.now());
        log.setIpAddress(getClientIp(request));
        log.setStatus(success ? 1 : 0);

        operateLogRepository.save(log);
    }

    public void recordLogoutLog(Integer userId, HttpServletRequest request) {
        OperateLog log = new OperateLog();
        log.setUserId(userId);
        log.setOperateType("logout");
        log.setOperateDetail(String.format("用户ID[%d]从IP[%s]登出系统", userId, getClientIp(request)));
        log.setOperateTime(LocalDateTime.now());
        log.setIpAddress(getClientIp(request));
        log.setStatus(1); // 登出总是成功

        operateLogRepository.save(log);
    }

    public void recordExportLog(User operator, int exportCount,HttpServletRequest request) {
        OperateLog log = new OperateLog();
        log.setUserId(operator.getUserId());
        log.setOperateType("export");
        log.setOperateDetail(String.format(
                "用户[%s](ID:%d)导出了%d条数据",
                operator.getRealName(),
                operator.getUserId(),
                exportCount
        ));
        log.setOperateTime(LocalDateTime.now());
        log.setIpAddress(getClientIp(request));
        log.setStatus(1); // 1表示成功

        operateLogRepository.save(log);
    }

    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
